<?php
declare (strict_types = 1);

namespace app\middleware;

class CorsMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 设置允许所有来源的请求
        header('Access-Control-Allow-Origin: *');
        // 设置允许的请求方法
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        // 设置允许的请求头
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        if ($request->method() === 'OPTIONS') {
            // 对于预检请求，直接返回200状态码
            return response('', 200);
        }
        return $next($request);
    }
}
